package com.example.yangjintingtest.controller;

import com.example.yangjintingtest.domain.BlogComment;
import com.example.yangjintingtest.mapper.CommentMapper;
import com.example.yangjintingtest.service.CommentService;
import com.example.yangjintingtest.service.SiteService;
import com.vdurmont.emoji.EmojiParser;
import io.micrometer.common.util.StringUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import com.example.yangjintingtest.domain.BlogArticle;
import com.example.yangjintingtest.domain.Statistic;
import com.example.yangjintingtest.mapper.BlogArticleMapper;
import com.example.yangjintingtest.mapper.StatisticMapper;
import com.example.yangjintingtest.utils.Commons;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
public class IndexController {
    private static final Logger logger = LoggerFactory.getLogger(IndexController.class);
    @Autowired
    CommentService commentService;
    @Autowired
    SiteService siteService;
    @Autowired
    CommentMapper commentMapper;
    // 发布文章
    public void publish (BlogArticle article) {
// 去除表情
        article.setContent (EmojiParser.parseToAliases (article.getContent ()));
        article.setCreated (new Date());
        article.setHits (0);
        article.setCommentsNum (0);
// 插入文章，同时插入文章统计数据
        blogArticleMapper.publishArticle (article);
        statisticMapper.addStatistic (article);
    }
    // 更新文章
    public void updateArticleWithId (BlogArticle article) {
        article.setModified (new Date ());
        blogArticleMapper.updateArticleWithId (article);
//        redisTemplate.delete ("article_" + article.getId ());
    }
    // 删除文章
    public void deleteArticleWithId (int id) {
// 删除文章的同时，删除对应的缓存
        blogArticleMapper.deleteArticleWithId (id);
//        redisTemplate.delete ("article_" + id);
// 同时删除对应文章的统计数据
        statisticMapper.deleteStatisticWithId (id);
// 同时删除对应文章的评论数据
        commentMapper.deleteCommentWithId (id);
    }
    // 查询文章的评论信息，并补充到文章详情里面
    private void getArticleComments (HttpServletRequest request, BlogArticle article) {
        if (article.getAllowComment ()) {
//cp 表示评论页码，commentPage
            String cp = request.getParameter ("cp");
            cp = StringUtils.isBlank (cp)? "1" : cp;
            request.setAttribute ("cp", cp);
            PageInfo<BlogComment> comments = commentService.getComments(article.getId(), Integer.parseInt(cp), 3);
            request.setAttribute("cp", cp);
            request.setAttribute("comments", comments);
        }
    }
    // 文章详情查询
    @GetMapping (value = "/article/{id}")
    public String getArticleById (@PathVariable ("id") Integer id, HttpServletRequest request) {
        BlogArticle article = blogArticleMapper.selectArticleWithId (id);
        HttpSession session = request.getSession();
        if (article!=null) {
// 查询封装评论相关数据
            getArticleComments (request, article);
// 更新文章点击量
            siteService.updateStatistics (article);
            request.setAttribute ("article",article);
            request.setAttribute("commons",commons);
            Object user = session.getAttribute("user");
            request.setAttribute("user",user);
            return "client/articleDetails";
        } else {
            logger.warn ("查询文章详情结果为空，查询文章 id:"+id);
// 未找到对应文章页面，跳转到提示页
            return "comm/error_404";
        }
    }
    @Autowired
    BlogArticleMapper blogArticleMapper;
    @Autowired
    StatisticMapper statisticMapper;
    @Autowired
    Commons commons;

    // 统计前10的热度文章信息
    public List<BlogArticle> getHeatArticles() {
        List<Statistic> list = statisticMapper.getStatistic();
        List<BlogArticle> articleList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            BlogArticle article = blogArticleMapper.selectArticleWithId(list.get(i).getArticleId());//根据文章id获取文章
            article.setHits(list.get(i).getHits());//统计文章点击量
            article.setCommentsNum(list.get(i).getCommentsNum());//统计文章评论数
            articleList.add(article);
            if (i >= 9) {
                break;
            }
        }
        return articleList;
    }

    // 分页查询文章列表
    public PageInfo<BlogArticle> selectArticleWithPage(Integer page, Integer count) {
        PageHelper.startPage(page, count);
        List<BlogArticle> articleList = blogArticleMapper.selectArticleWithPage();
        // 封装文章统计数据
        for (int i = 0; i < articleList.size(); i++) {
            BlogArticle article = articleList.get(i);
            Statistic statistic = statisticMapper.selectStatisticWithArticleId(article.getId());
            article.setHits(statistic.getHits());
            article.setCommentsNum(statistic.getCommentsNum());
        }
        PageInfo<BlogArticle> pageInfo = new PageInfo<>(articleList);
        return pageInfo;
    }

    // 博客首页，会自动跳转到文章页
    @GetMapping(value = "/")
    private String index(Model model) { return this.index(model, 1, 5); }

    // 文章页
    @GetMapping(value = "/page/{p}")
    public String index(Model model, @PathVariable("p") int page, @RequestParam(value = "count", defaultValue = "5") int count) {
        PageHelper.startPage(page, count);
        PageInfo<BlogArticle> articles = selectArticleWithPage(page, count);
        // 获取文章热度统计信息
        List<BlogArticle> articleList = getHeatArticles();
        model.addAttribute("articles", articles);
        model.addAttribute("articleList", articleList);
        return "client/index1";
    }
}